package xyz.xpman.prisonerfitness.dao;

import android.content.Context;
import android.content.SharedPreferences;

import androidx.arch.core.util.Function;

import org.jetbrains.annotations.NotNull;

import xyz.xpman.prisonerfitness.entity.User;
import xyz.xpman.prisonerfitness.util.StrKit;


/**
 * SharedPreferencesCache
 */
public class SpLocalCache implements ILocalCache {

    private static final String USER_SP_KEY = "loginUser";

    private final SharedPreferences sp;
    private final Function<String, User> func;


    public SpLocalCache(
            @NotNull Context context, @NotNull Function<String, User> func) {

        this.func = func;
        this.sp = context.getSharedPreferences(USER_SP_KEY, Context.MODE_PRIVATE);
    }


    @Override
    public boolean saveLoggedInUserId(int id) {
        SharedPreferences.Editor spEdit = sp.edit();
        spEdit.putString(USER_SP_KEY, String.valueOf(id));
        return spEdit.commit();
    }


    @Override
    public boolean removeLoggedInUserId() {
        SharedPreferences.Editor spEdit = sp.edit();
        spEdit.remove(USER_SP_KEY);
        return spEdit.commit();
    }

    @Override
    public Integer getLoggedInUserId() {
        String id = sp.getString(USER_SP_KEY, null);
        Integer num = null;

        if (StrKit.notBlank(id)) {
            num = Integer.parseInt(id);
        }
        return num;
    }


    @Override
    public User getCurrentUser() {
        Integer id = getCurrentUserId();

        if (null != id) {
            return func.apply(String.valueOf(id));
        }
        return null;
    }


    @Override
    public Integer getCurrentUserId() {
        return getLoggedInUserId();
    }

}
